package com.rehome.udp;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.*;

public class UDPServer implements ActionListener, Runnable {
    private DatagramSocket datagramSocket;
    private Thread thread = null;
    private UDPFrame serverFrame;

    public UDPServer() {
        serverFrame = new UDPFrame("UDPServer");
        JPanel panel = new JPanel();
        serverFrame.add(panel);

        serverFrame.placeComponents(panel);
        serverFrame.setVisible(true);

        //port:8888
        serverFrame.getConnect().addActionListener(e -> {
            try {
                int dSocketPort = Integer.parseInt(serverFrame.getDSocketField().getText());
                datagramSocket = new DatagramSocket(dSocketPort);

                serverFrame.getTextArea().append("[连接] : 正在连接中……\n");
                serverFrame.getTextArea().append("\t连接成功\n");

                thread = new Thread(this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        serverFrame.getTransmit().addActionListener(this);
        serverFrame.getTextArea().append("……UDP服务器启动……\n");
        System.out.println("……UDP服务器启动……\n");
    }

    public static void main(String[] args) {
        new UDPServer();
    }

    //向客户端发送数据
    @Override
    public void actionPerformed(ActionEvent e) {
        new UDPSend(datagramSocket, serverFrame, "服务器端").sendMessages();
    }

    //使用线程处理服务器端接收客户端的数据
    @Override
    public void run() {
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        new UDPReceive(datagramSocket, datagramPacket, serverFrame, "客户端").receiveMessages();
    }
}

